package com.frejoys.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.frejoys.common.dto.admin.UserLevelMoneyListDto;
import com.frejoys.common.enums.EUserLevelType;
import com.frejoys.common.util.AppConfigUtil;
import com.frejoys.common.vo.admin.UserLevelMoneyListVo;
import com.frejoys.dao.entity.User;
import com.frejoys.dao.entity.UserLevelMoney;
import com.frejoys.dao.mapper.UserLevelMoneyMapper;
import com.frejoys.dao.mapper.UserMapper;
import com.frejoys.service.UserLevelMoneyService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
@RequiredArgsConstructor
public class UserLevelMoneyServiceImpl  extends ServiceImpl<UserLevelMoneyMapper, UserLevelMoney> implements UserLevelMoneyService {

    private final UserMapper userMapper;

    @Override
    public boolean addIfNot(Long userId, Long childUserId) {

        LambdaQueryWrapper<UserLevelMoney> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(UserLevelMoney::getId)
                .eq(UserLevelMoney::getUserId,userId)
                .eq(UserLevelMoney::getChildUserId,childUserId);
        UserLevelMoney userLevelMoney = getOnly(wrapper);

        if (userLevelMoney == null){
            save(new UserLevelMoney(){{
                setUserId(userId);
                setChildUserId(childUserId);
                setMoney(BigDecimal.ZERO);
            }});
        }
        return true;
    }

    @Override
    public IPage<UserLevelMoneyListVo> userLevelMoneyListInfo(UserLevelMoneyListDto dto) {
        Page page = new Page<>(dto.getPage(), dto.getSize());

        LambdaQueryWrapper<UserLevelMoney> wrapper = new LambdaQueryWrapper<>();

        if (dto.getStatus() == EUserLevelType.userLevelTypeUser.getValue()){

            if (dto.getUserId() != null){
                wrapper.eq(UserLevelMoney::getUserId,dto.getUserId());
            }
            if (StrUtil.isNotEmpty(dto.getPhone())){
                Long userId = userMapper.phoneByUserId(dto.getPhone());

                if (userId == null){
                    return new Page<>();
                }
                wrapper.eq(UserLevelMoney::getUserId,userId);
            }
            if (StrUtil.isNotEmpty(dto.getNickname())){
                List<Long> userIds = userMapper.nicknameByUserId(dto.getNickname());

                if (userIds.isEmpty()){
                    return new Page<>();
                }
                wrapper.in(UserLevelMoney::getUserId,userIds);
            }
        }

        if (dto.getStatus() == EUserLevelType.childUser.getValue()){

            if (dto.getUserId() != null){
                wrapper.eq(UserLevelMoney::getChildUserId,dto.getUserId());
            }
            if (StrUtil.isNotEmpty(dto.getPhone())){
                Long userId = userMapper.phoneByUserId(dto.getPhone());

                if (userId == null){
                    return new Page<>();
                }
                wrapper.eq(UserLevelMoney::getChildUserId,userId);
            }
            if (StrUtil.isNotEmpty(dto.getNickname())){
                List<Long> userIds = userMapper.nicknameByUserId(dto.getNickname());

                if (userIds.isEmpty()){
                    return new Page<>();
                }
                wrapper.in(UserLevelMoney::getChildUserId,userIds);
            }
        }

        Page<UserLevelMoney> userLevelMoneyPage = baseMapper.selectPage(page, wrapper);
        IPage<UserLevelMoneyListVo> voIPage = userLevelMoneyPage.convert(userLevelMoney -> BeanUtil.copyProperties(userLevelMoney, UserLevelMoneyListVo.class));
        List<UserLevelMoneyListVo> list = voIPage.getRecords();

        if (!list.isEmpty()){
            // 推荐人id
            List<Long> userIds = list.stream().map(UserLevelMoneyListVo::getUserId).toList();

            // 被推荐人id
            List<Long> childUserIds = list.stream().map(UserLevelMoneyListVo::getChildUserId).toList();

            List<Long> ids = Stream.of(userIds, childUserIds).flatMap(List::stream).distinct().collect(Collectors.toList());

            List<User> users = userMapper.getUserByIds(ids);
            Map<Long, User> userMap = users.stream().collect(Collectors.toMap(User::getId, user -> user));

            list.forEach(vo ->{

                if (userMap.containsKey(vo.getUserId())){
                    User user = userMap.get(vo.getUserId());
                    vo.setNickname(user.getNickname());
                    vo.setAvatar(AppConfigUtil.getUrlPrefix(user.getAvatar()));
                    vo.setPhone(user.getPhone());
                }
                if (userMap.containsKey(vo.getChildUserId())){
                    User user = userMap.get(vo.getChildUserId());
                    vo.setChildNickname(user.getNickname());
                    vo.setChildAvatar(AppConfigUtil.getUrlPrefix(user.getAvatar()));
                    vo.setChildPhone(user.getPhone());
                }
            });
        }
        return voIPage;
    }
}
